<template>
  <div>
    <van-nav-bar title="登陆/注册" left-arrow @click-left="$router.back()" />
    <van-form ref="FormRef" @submit="onlogin" @failed='onFail' validate-first :show-error-message='false' :show-error='false'>
      <van-field center name="mobile" clearable v-model="user.mobile" icon-prefix="toutiao" left-icon="shouji" placeholder="手机号" :rules="Rules.mobile" />
      <van-field name="code" clearable center v-model="user.code" icon-prefix="toutiao" left-icon="yanzhengma" placeholder="验证码" :rules="Rules.code">
        <template #button>
          <van-count-down v-if="isCountDownShow" :time="1000 * 10" format="ss s" @finish="isCountDownShow = false" />
          <van-button v-else size="mini" round :loading="isSendSmsLoading" @click.prevent="onSendSms">发送验证码</van-button>
        </template>
      </van-field>
      <div style="margin: 16px;">
        <van-button round block type="info">
          提交
        </van-button>
      </div>
    </van-form>
  </div>
</template>
<script>
import { login, sendSms } from '@/api/user.js'
export default {
  name: 'login',
  data() {
    return {
      user: {
        mobile: '13911111111',
        code: '246810'
      },
      Rules: {
        mobile: [
          { required: true, message: '请填写手机号', trigger: 'onSubmit' },
          { pattern: /^1[3|5|8|9]\d{9}$/, message: '请填合法手机号', trigger: 'onSubmit' }
        ],
        code: [
          { required: true, message: '请填写验证码' },
          { pattern: /\d{6}$/, message: '请填写合法验证码' }
        ]
      },
      isSendSmsLoading: false,
      isCountDownShow: false,
      finish: false
    }
  },
  methods: {
    async onlogin() {
      this.$toast.loading({
        message: '登陆中',
        forbidClick: true
      })
      try {
        const { data: res } = await login(this.user)
        this.$store.commit('setUser', res.data)
        this.$router.push('/my')
        this.$toast.success('登陆成功')
      } catch (error) {
        this.$toast.fail('登陆失败，手机号或验证码错误')
      }
    },
    async onSendSms() {
      try {
        await this.$refs.FormRef.validate('mobile')
        this.isSendSmsLoading = true
        await sendSms(this.user.mobile)
        this.isCountDownShow = true
      } catch (err) {
        let message = null
        if (err && err.response && err.response.status === 429) {
          message = '发送太频繁了，请稍后重试'
        } else if (err.name === 'mobile') {
          message = err.message
        } else {
          message = '发送失败，请稍后重试'
        }
        this.$toast({ message, position: 'top' })
      }
      this.isSendSmsLoading = false
    },
    //  message = '发送太频繁了，请稍后重试'
    //  message = '发送失败，请稍后重试'
    onFail(error) {
      if (error.errors[0]) {
        this.$toast({
          message: error.errors[0].message,
          position: 'top'
        })
      }
    }
  }
}
</script>
<style lang="less" scoped>
</style>
